import { AdvancedSearch, DATA_ENTRY, ContentPackage, FirstHeaderC } from '@/comps/index';
import React, { useRef, useEffect, useState } from 'react';
import moment from 'moment';
import styles from './index.less';
import { namespace } from '@/src/newModels/leverageAnalysis/OperationalMonitoringLeverageAnalysisM';
import { connect } from 'dva';
import TitleTableC from '@/src/routes/PortfolioManagement/leverageAnalysis/TitleTable';
import dictionaryConfig from '@/src/utils/dictionaryConfig';
import { times } from 'number-precision';
import { Spin } from 'antd';
import { reservedBits } from '@/src/utils/commonFunc';
// 查询id

let timerForQuery;
export default connect(({ loading, globalM }) => ({ loading, globalM }))((props) => {
  const { dispatch } = props;
  const dateRef = useRef(); // 日期范围ref
  const tableRef1 = useRef(null); // table ref
  const tableRef2 = useRef(null); // table ref
  const tableRef3 = useRef(null); // table ref
  const tableRef4 = useRef(null); // table ref 倾向分析
  const [tradingDate, setTradingDate] = useState();
  const [loadingForSearch, setLoadingForSearch] = useState(false);
  const [dateRange, setDateRange] = useState({
    startDate: undefined,
    endDate: undefined,
  }); // 时间区间
  // 初始化查询栏数据
  const initQuery = (previousDate) => {
    timerForQuery = setInterval(() => {
      if (dateRef.current.state.SelectC) {
        clearInterval(timerForQuery);
        dateRef.current.setSelctAndDate('5', moment().subtract(3, 'M').add(0, 'd'), moment(previousDate));
        setDateRange({
          ...dateRange,
          endDate: previousDate || moment().format('YYYY-MM-DD'),
          startDate: moment().subtract(3, 'M').add(0, 'd').format('YYYY-MM-DD'),
        });
      }
    }, 100);
  };
  const getTradingDate = () => {
    setLoadingForSearch(true);
    dispatch({
      type: `globalM/getTradingDate`,
      payload: { type: '2' },
      callback: (res) => {
        setLoadingForSearch(false);
        setTradingDate(moment(res).format('YYYY-MM-DD')); // Previous前交易日
        initQuery(moment(res).format('YYYY-MM-DD')); // 初始化查询栏数据
      },
    });
  };
  useEffect(() => {
    getTradingDate();
  }, []);
  const handleSearch = (e) => {
    console.log(11111111, tradingDate);
    if (!e) {
      initQuery(tradingDate);
      setDateRange({
        ...dateRange,
        endDate: tradingDate || moment().format('YYYY-MM-DD'),
        startDate: moment().subtract(3, 'M').add(0, 'd').format('YYYY-MM-DD'),
      });
      tableRef1.current?.reset();
      tableRef2.current?.reset();
      tableRef3.current?.reset();
      tableRef4.current?.reset();
      return;
    }
    setDateRange({
      ...dateRange,
      startDate: e.startDate.format('YYYY-MM-DD'),
      endDate: e.endDate.format('YYYY-MM-DD'),
    });
  };

  const searchProps = {
    dataSource: [
      {
        previousDateType: 2,
        selectIndex: 'complextdate1',
        startIndex: 'startDate',
        endIndex: 'endDate',
        hasDataED: moment(tradingDate),
        type: DATA_ENTRY.COMPLEXDATE,
        selfDefination: ['0', '4', '5', '6', '7'],
        initialValue: '2',
        onRef: (ref) => (dateRef.current = ref),
      },
    ],
    onQuery: handleSearch,
    onClear: handleSearch,
  };

  /**
   * 格式化杠杆率范围的值
   * @param recordObj key值对象
   * @returns {string}
   */
  const showLeverageRange = (recordObj = {}) => {
    if (!recordObj) return '--';
    const { min, max, judgeSymbol } = recordObj;
    if (judgeSymbol === '-') return `${times(min ?? 0, 100)}%${judgeSymbol}${times(max ?? 0, 100)}%`;
    if (judgeSymbol === '<') return `${judgeSymbol}${times(max ?? 0, 100)}%`;
    if (judgeSymbol === '>') return `${judgeSymbol}${times(min ?? 0, 100)}%`;
    return '--';
  };
  /**
   * 百分比高亮颜色
   * @returns {string}
   * @param partition
   */
  const showRangeYearRateColor = (partition) => {
    if (partition === '1') return '#E5F8F3';
    if (partition === '2') return '#FDFAEA';
    if (partition === '3') return '#D9E4FF';
    if (partition === '4') return '#FFE5E5';
    return 'unset';
  };
  // 分位数统计
  const columns1 = [
    { key: 'maxLeverageRange', title: '最大杠杆率范围', width: 120, align: 'left', render: (_, record) => showLeverageRange(record.maxLeverageRange) },
    {
      key: 'maxQuantiles',
      title: '分位数（%）',
      width: 120,
      align: 'left',
      render: (text) => {
        if (!text && text !== 0) return '--';
        return reservedBits(Number.parseFloat(times(text, 100)));
      },
    },
    { key: 'averageLeverageRange', title: '平均杠杆率范围', width: 120, align: 'left', render: (_, record) => showLeverageRange(record.averageLeverageRange) },
    {
      key: 'averageQuantiles',
      title: '分位数（%）',
      width: 120,
      align: 'right',
      render: (text) => {
        if (!text && text !== 0) return '--';
        return reservedBits(Number.parseFloat(times(text, 100)));
      },
    },
  ];
  // 收益贡献分析
  const columns2 = [
    { key: 'productName', title: '产品名称', width: 210, align: 'left', render: (_, record) => (_ ? `${record.productCode}-${record.productName}` : '--') },
    { key: 'tenant', title: '所属租户', width: 160, align: 'right' },
    {
      key: 'maxLeverage',
      title: '最高杠杆率（%）',
      width: 120,
      align: 'right',
      render: (text) => {
        if (!text && text !== 0) return '--';
        return reservedBits(Number.parseFloat(times(text, 100)));
      },
    },
    { key: 'maxLeverageDate', title: '日期', width: 120, align: 'right' },
    {
      key: 'minLeverage',
      title: '最低杠杆率（%）',
      width: 120,
      align: 'right',
      render: (text) => {
        if (!text && text !== 0) return '--';
        return reservedBits(Number.parseFloat(times(text, 100)));
      },
    },
    { key: 'minLeverageDate', title: '日期', width: 120, align: 'right' },
    {
      key: 'averageLeverage',
      title: '平均杠杆率（%）',
      width: 120,
      align: 'right',
      render: (text) => {
        if (!text && text !== 0) return '--';
        return reservedBits(Number.parseFloat(times(text, 100)));
      },
    },
    {
      key: 'differenceLever',
      title: '杠杆差（%）',
      width: 120,
      align: 'right',
      render: (text) => {
        if (!text && text !== 0) return '--';
        return reservedBits(Number.parseFloat(times(text, 100)));
      },
    },
    {
      key: 'rangeYearRate',
      title: '区间年化收益率（%）',
      width: 120,
      align: 'right',
      className: 'maat-column-cell',
      onCell: (record) => {
        const cellProps = {};
        cellProps.style = {
          background: showRangeYearRateColor(record.partition),
        };
        return cellProps;
      },
      render: (text) => {
        if (text === null) return '--';
        const num = times(Number(text) * 100);
        return <div>{`${reservedBits(Number.parseFloat(num))}%`}</div>;
      },
    },
  ];
  // 倾向分析
  const columns3 = [
    { key: 'tenant', title: '租户名称', width: 120, align: 'left' },
    {
      key: 'maxLeverage',
      title: '最高杠杆率（%）',
      width: 120,
      align: 'right',
      render: (text) => {
        if (!text && text !== 0) return '--';
        return reservedBits(Number.parseFloat(times(text, 100)));
      },
    },
    {
      key: 'minLeverage',
      title: '最低杠杆率（%）',
      width: 120,
      align: 'right',
      render: (text) => {
        if (!text && text !== 0) return '--';
        return reservedBits(Number.parseFloat(times(text, 100)));
      },
    },
    {
      key: 'averageLeverage',
      title: '平均杠杆率（%）',
      width: 120,
      align: 'right',
      render: (text) => {
        if (!text && text !== 0) return '--';
        return reservedBits(Number.parseFloat(times(text, 100)));
      },
    },
    {
      key: 'differenceLever',
      title: '杠杆差（%）',
      width: 120,
      align: 'right',
      render: (text) => {
        if (!text && text !== 0) return '--';
        return reservedBits(Number.parseFloat(times(text, 100)));
      },
    },
  ];
  const { cashManage, openPublicOffering, closedAndOthers } = dictionaryConfig.leverageUpperLimit;
  return (
    <ContentPackage
      title='杠杆率分析'
      contentHtml={
        <div className={styles.LeverageAnalysisForOperationalMonitoring}>
          <Spin spinning={loadingForSearch}>
            <AdvancedSearch {...searchProps} />
          </Spin>
          <div style={{ margin: '20px 0' }}>
            <FirstHeaderC title='分位数统计' />
            <div>
              <TitleTableC
                dateRange={dateRange}
                columns={columns1}
                effect={`${namespace}/queryQuantileStatistics`}
                payloadType={{ productType: 1 }}
                title={`现金管理类：上限${cashManage}%`}
                isPagination={false}
              />
              <TitleTableC
                dateRange={dateRange}
                columns={columns1}
                effect={`${namespace}/queryQuantileStatistics`}
                payloadType={{ productType: 2 }}
                title={`开放式公募：上限${openPublicOffering}%`}
                isPagination={false}
              />
              <TitleTableC
                dateRange={dateRange}
                columns={columns1}
                effect={`${namespace}/queryQuantileStatistics`}
                payloadType={{ productType: 3 }}
                title={`封闭式及其他：上限${closedAndOthers}%`}
                isPagination={false}
              />
            </div>
            <FirstHeaderC title='收益贡献分析' />
            <div className={styles.allTables}>
              <TitleTableC
                ref={tableRef1}
                dateRange={dateRange}
                columns={columns2}
                effect={`${namespace}/queryRevenueAnalysis`}
                payloadType={{ productType: 1 }}
                title={`现金管理类：上限${cashManage}%`}
                sorterKeys={['maxLeverage', 'minLeverage', 'averageLeverage', 'rangeYearRate', 'differenceLever']}
              />
              <TitleTableC
                ref={tableRef2}
                dateRange={dateRange}
                columns={columns2}
                effect={`${namespace}/queryRevenueAnalysis`}
                payloadType={{ productType: 2 }}
                title={`开放式公募：上限${openPublicOffering}%`}
                sorterKeys={['maxLeverage', 'minLeverage', 'averageLeverage', 'rangeYearRate', 'differenceLever']}
              />
              <TitleTableC
                ref={tableRef3}
                dateRange={dateRange}
                columns={columns2}
                effect={`${namespace}/queryRevenueAnalysis`}
                payloadType={{ productType: 3 }}
                title={`封闭式及其他：上限${closedAndOthers}%`}
                sorterKeys={['maxLeverage', 'minLeverage', 'averageLeverage', 'rangeYearRate', 'differenceLever']}
              />
            </div>
            <FirstHeaderC title='倾向分析' />
            <TitleTableC
              sorterKeys={['maxLeverage', 'minLeverage', 'averageLeverage', 'differenceLever']}
              ref={tableRef4}
              dateRange={dateRange}
              columns={columns3}
              effect={`${namespace}/queryPropensityAnalysis`}
              payloadType={{}}
              title={null}
            />
          </div>
        </div>
      }
    />
  );
});
